package Daos;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Expression;

/**
 *
 */
public abstract class DaoGenerico<T> {

    private Object object;
    private Session sessao;
    private Criteria criteria;
    private Class objectClass;

    public Session getSessao(){
        return this.sessao;
    }

    public DaoGenerico() {
        begin();
    }

    public DaoGenerico(Object object) {
        this.object = object;
    }

    private Class getObjectClass() {
        objectClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return objectClass;
    }

    private void commit() {
        this.sessao.beginTransaction().commit();
        this.sessao.flush();
        this.sessao.close();
    }

    private void begin() {
        sessao = Mapeador.getSessao();
        criteria = sessao.createCriteria(getObjectClass());
        sessao.beginTransaction().begin();
    }

    public List<T> get() {
        return listResult(criteria);
    }

    public T get(Long id) {
        return uniqueResult(criteria.add(Expression.eq("id", id)));
    }
    public List<T> get(Long... ids) {
        criteria.add(Expression.in("id", ids));
        
        return listResult(criteria);
    }

    public T uniqueResult(Criteria cri) {
        T ret = (T) cri.uniqueResult();
        commit();
        return ret;

    }

    public List<T> listResult(Criteria cri) {
        List ret = cri.list();
        commit();
        return ret;
    }
    
    public Boolean valida;

    public void update() {
        begin();
        this.sessao.update(object);
        commit();
    }

    public void delete() {
        begin();
        this.sessao.delete(object);
        commit();
    }

    public void persist() {
        begin();
        this.sessao.saveOrUpdate(object);
        commit();
    }
    
    public List<T> getPorString(String where) {
        String [] merda = where.split("=");
        this.criteria.add(Expression.eq(merda[0], merda[1]));
        
         return  listResult(criteria);

    }
}
